import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AlertController } from '@ionic/angular';

@Component({
  selector: 'app-detail',
  templateUrl: './detail.page.html',
  styleUrls: ['./detail.page.scss'],
})
export class DetailPage implements OnInit {
  constructor(
    public route: ActivatedRoute,
    public http: HttpClient,
    public alertC: AlertController
  ) {}

  res: Result;

  addToCard() {
    const lid = this.route.snapshot.params.lid;
    const url = '/api/data/cart/add.php?buyCount=1&lid=' + lid;

    this.http.get(url, { withCredentials: true }).subscribe((res: any) => {
      console.log(res);
      if (res.code == 200) {
        // alert('添加成功!');
        this.alertC.create({ header: '添加成功' }).then((res) => res.present());
      }
    });
  }

  ngOnInit() {
    const lid = this.route.snapshot.params.lid;

    const url = 'http://101.96.128.94:9999/data/product/details.php?lid=' + lid;

    this.http.get(url).subscribe((res: Result) => {
      console.log(res);
      // 修改返回值中的 html 的 src, 添加域名前缀
      // 原格式: src="img
      // 修改成: src="http://101.96.128.94:9999/img
      res.details.details = res.details.details.replace(
        /src="img/g, // 搜索所有此格式的字符串
        'src="http://101.96.128.94:9999/img' //替换成这个
      );

      res.details.details = res.details.details.replace(
        // \ 是转义符
        /src="\/\/img20/g, // 搜索所有此格式的字符串
        'src="https://img20' //替换成这个
      );

      this.res = res;
    });
  }
}

////////////////
interface Result {
  details: ResultDetail;
  // 页面不使用 family, 就不写了
  family: any;
}

interface ResultDetail {
  category: string;
  cpu: string;
  details: string;
  disk: string;
  family_id: string;
  is_onsale: string;
  lid: string;
  lname: string;
  memory: string;
  os: string;
  picList: PicList[];
  price: string;
  promise: string;
  resolution: string;
  shelf_time: string;
  sold_count: string;
  spec: string;
  subtitle: string;
  title: string;
  video_card: string;
  video_memory: string;
}

interface PicList {
  laptop_id: string;
  lg: string;
  md: string;
  pid: string;
  sm: string;
}
